import React, { Component, PropTypes } from "react";
import { connect } from "react-redux";
import { messages, deepFullCopy } from "share/common";
import { Form, Button, Switch, message, Modal, Row } from "antd";
import errorMessage from "share/errorMessage";
import Priority from "components/template/priority";
import Condition from "components/condition";
import requestService from "./request-and-expense-settings.service";
import "styles/request-and-expense-settings/slide-frame-content.scss";

const { If } = Condition;

const FormItem = Form.Item;

class SlideFrameDetail extends Component {
  //为了区分启用公司 是通用还是部分，要处理一下distribution属性
  handlePriorityInfo = (priorityValue) => {
    if (
      priorityValue.distribution &&
      priorityValue.distribution.companies &&
      !priorityValue.distribution.companies.length
    ) {
      delete priorityValue.distribution;
    }
    return priorityValue;
  };

  state = {
    loading: false,
    enabled: this.props.enabled,
    priorityValue: this.handlePriorityInfo(this.props.priorityInfo.value || {}),
  };

  setValues = (values) => {
    this.props.form.setFieldsValue(values);
  };

  //取消拆单配置
  handleCancelSplitProfile = (e) => {
    this.setState({ loading: true });
    requestService
      .cancelSplitProfile()
      .then(() => {
        this.handleSave(e);
      })
      .catch((err) => {
        this.setState({ loading: false });
        errorMessage(err.response);
      });
  };

  //渲染拆单确认框
  renderConfirmModal = (e) => {
    return Modal.confirm({
      title: messages(
        "expense-2.key48"
      ) /*配置拆单则无法使用发票袋，是否去掉拆单？*/,
      content: (
        <div>
          <Row style={{ color: "#f5222d" }}>
            {
              messages(
                "expense-2.key49"
              ) /*去掉拆单，报销单将不按照费用类型拆单。*/
            }
          </Row>
          <Row>{messages("expense-2.key50") /*你还要继续吗？*/}</Row>
        </div>
      ),
      okText: messages("expense-2.key51") /*继续*/,
      width: 450,
      iconType: "exclamation-circle",
      onOk: () => this.handleCancelSplitProfile(e),
    });
  };

  handleSave = (e) => {
    e.preventDefault();
    const {
      priorityInfo,
      service,
      dealParams,
      checkBeforeSave,
      onlyCompaniesId,
    } = this.props;
    const { priorityValue } = this.state;
    let companies = [];
    if (priorityInfo.top && !(priorityValue && priorityValue.levelCode)) {
      message.error(messages("expense-2.key52") /*请选择所属组织*/);
      return;
    }
    if (
      priorityValue &&
      priorityValue.levelCode === priorityInfo.top &&
      priorityValue.distribution &&
      priorityValue.distribution.companies &&
      priorityValue.distribution.companies.length === 0
    ) {
      message.error(messages("expense-2.key53") /*请选择启用公司*/);
      return;
    }
    if (priorityValue.distribution && priorityValue.distribution.companies) {
      priorityValue.distribution.companies.map((item) =>
        companies.push(item.id)
      );
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        checkBeforeSave(values)
          .then(() => {
            if (priorityInfo.top) {
              values.levelCode = priorityValue.levelCode;
              values.levelOrgId = priorityValue.levelOrgId;
              values.companies = onlyCompaniesId
                ? companies
                : (priorityValue.distribution || {}).companies || [];
            }
            this.setState({ loading: true });
            let params = dealParams(deepFullCopy(values));
            service(params)
              .then((res) => {
                this.setState({ loading: false });
                if (res.data && res.data.code === "5006019") {
                  //配置了拆单
                  this.renderConfirmModal(e);
                  return;
                }
                message.success(
                  res.data.msg ||
                    messages("common.operate.success") /*操作成功*/
                );
                this.props.close(true);
              })
              .catch((e) => {
                this.setState({ loading: false });
                errorMessage(e.response);
              });
          })
          .catch((err) => {
            message.error(err);
          });
      }
    });
  };

  handlePriorityChange = (value) => {
    const {
      onPriorityChange,
      form: { getFieldValue, setFieldsValue },
    } = this.props;
    this.setState({ priorityValue: value });
    if (
      getFieldValue("forcedRelatedForm") &&
      +getFieldValue("forcedRelatedForm").forcedRelatedType === 1001
    ) {
      setFieldsValue({
        forcedRelatedForm: Object.assign(
          {},
          getFieldValue("forcedRelatedForm"),
          { forcedRelatedFormIDs: [] }
        ),
      });
    }
    if (
      getFieldValue("unforcedRelatedForm") &&
      +getFieldValue("unforcedRelatedForm").unforcedRelatedType === 1001
    ) {
      setFieldsValue({
        unforcedRelatedForm: Object.assign(
          {},
          getFieldValue("unforcedRelatedForm"),
          { unforcedRelatedFormIDs: [] }
        ),
      });
    }
    onPriorityChange && onPriorityChange(value);
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { enabledKey, formInfo, priorityInfo, disabled } = this.props;
    const { loading, enabled } = this.state;
    return (
      <div className="slide-frame-content">
        <Form className="new-form" onSubmit={this.handleSave}>
          <FormItem label={messages("common.column.status") /*状态*/}>
            {getFieldDecorator(enabledKey || "enabled", {
              valuePropName: "checked",
              initialValue: enabled,
            })(
              <Switch
                disabled={disabled}
                onChange={(enabled) => this.setState({ enabled })}
              />
            )}
            <span className="switch-desc">
              {
                enabled
                  ? messages("common.status.enable") /*启用*/
                  : messages("common.status.disable") /*禁用*/
              }
            </span>
          </FormItem>
          <If value={priorityInfo.top}>
            <Priority
              disabled={disabled}
              disabledTop={priorityInfo.disabled}
              companyProps={{ disabled: priorityInfo.disabled || disabled }}
              top={priorityInfo.top}
              formItemLayout={{}}
              defaultValue={priorityInfo.value}
              onlySetOfBooks={priorityInfo.onlySetOfBooks}
              showCompany={priorityInfo.showCompany}
              onChange={this.handlePriorityChange}
              required
              {...(priorityInfo.extraParams || {})}
            />
          </If>
          {formInfo.map((item) => (
            <div key={item.title}>
              <If value={item.title}>
                <div className="sub-title">{item.title}</div>
              </If>
              {item.list &&
                item.list
                  .filter((formItem) => !formItem.hide)
                  .map((formItem) => (
                    <FormItem
                      key={formItem.id}
                      label={formItem.label || " "}
                      extra={formItem.extra}
                      {...(formItem.extraProps || {})}
                    >
                      {getFieldDecorator(formItem.id, {
                        rules: formItem.rules || [],
                        initialValue: formItem.initialValue,
                      })(formItem.component)}
                    </FormItem>
                  ))}
              <div className="slide-footer">
                <If value={!disabled}>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    {messages("common.save") /*保存*/}
                  </Button>
                </If>
                <Button onClick={this.props.close}>
                  {messages("common.cancel") /*取消*/}
                </Button>
              </div>
            </div>
          ))}
        </Form>
      </div>
    );
  }

  static propTypes = {
    enabledKey: PropTypes.string,
    enabled: PropTypes.bool,
    disabled: PropTypes.bool,
    priorityInfo: PropTypes.object,
    formInfo: PropTypes.array,
    onlyCompaniesId: PropTypes.bool,
    service: PropTypes.func,
    dealParams: PropTypes.func,
    checkBeforeSave: PropTypes.func,
  };

  static defaultProps = {
    priorityInfo: {},
    onlyCompaniesId: true,
    dealParams: (values) => values,
    checkBeforeSave: () => new Promise((resolve) => resolve()),
  };
}

function mapStateToProps(state) {
  return {};
}

const WrappedSlideFrameDetail = Form.create()(SlideFrameDetail);

export default connect(mapStateToProps)(WrappedSlideFrameDetail);
